package com.yanguilai.rabbitmqexchange.send;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Component
public class ExchangePublish {

//    private final static String EXCHANGE_NAME = "direct_logs";
    private final static String EXCHANGE_NAME = "topic_logs";

    private static Channel channel;

    static {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("c7formal");
        try {
            Connection connection = factory.newConnection();
            channel = connection.createChannel();
//            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }

    public void publish(String msg) {
        try {
            channel.basicPublish(EXCHANGE_NAME, "", null, msg.getBytes());
            System.out.println(" [x] Sent '" + msg + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void publishBySeverity(String severity, String msg) {
        try {
            channel.basicPublish(EXCHANGE_NAME, severity, null, msg.getBytes());
            System.out.println(" [x] Sent '" + severity + "':'" + msg + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void publishTopic(String facility, String severity, String msg){
        try {
            channel.basicPublish(EXCHANGE_NAME, facility.concat(".").concat(severity), null, msg.getBytes());
            System.out.println(" [x] Sent '" + severity + "':'" + msg + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
